//
//  UIAlertControllerCustomer.m
//  UIAlerviewCustomer
//
//  Created by s on 16/6/12.
//  Copyright © 2016年 s. All rights reserved.
//

#import "CMCCIOTIGAlertControlCustomer.h"

@interface CMCCIOTIGAlertControlCustomer ()<UITextFieldDelegate>

#define  screenWidth  [UIScreen  mainScreen].bounds.size.width
#define  screenHeight [UIScreen  mainScreen].bounds.size.height
#define   btnTag 1000

@property(nonatomic,assign)UIAlertControllerCustomStyle  alertControllerstyle;
@property(nonatomic,strong)NSString  *alerTitle;
@property(nonatomic,strong)NSString  *alerMessage;
@property(nonatomic,strong)NSMutableArray  *arrTextField;
@property(nonatomic,strong)UIScrollView  *viewAlert;

@end

@implementation CMCCIOTIGAlertControlCustomer
@synthesize alerTitle,alerMessage,alertControllerstyle,lableMessage ;


- (void)drawRect:(CGRect)rect{
    //   添加弹出框界面
    [self initAlertView];
    //   注册键盘通知
    [self  initNotification ];

}
//返回UIAlertControllerCustomer  实例
+ (_Nonnull instancetype)alertControllerWithTitle:(NSString * _Nonnull )title message:( NSString * _Nonnull )message preferredStyle:(UIAlertControllerCustomStyle)preferredStyle{
    CMCCIOTIGAlertControlCustomer  *alertControllerCustomer=[[CMCCIOTIGAlertControlCustomer  alloc]  initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight)];
    alertControllerCustomer.backgroundColor=[UIColor clearColor];
    alertControllerCustomer.alerTitle=title;
    alertControllerCustomer.alerMessage=message;
    alertControllerCustomer.messageAlignment=NSTextAlignmentCenter;
    alertControllerCustomer.alertControllerstyle=preferredStyle;
    
    return alertControllerCustomer;

}

#pragma mark  添加提示框  UIAlertControllerStyleAlert 等几种样式
-(void)initAlertView{
    
//   如果是UIAlertControllerStyleAlert 显示
    if (self.alertControllerstyle==UIAlertControllerCustomStyleAlert ) {
        [self  setAlertView ];
    }
    //  UIAlertControllerCustomStyleVerticalStyle  界面
    else  if (self.alertControllerstyle==UIAlertControllerCustomStyleVerticalStyle){
        [self  setVerticalView];
    }  // 其他模式 ，方便扩展
    else{
    
    
    }

}

//UIAlertControllerStyleAlert 样式
-(void)setAlertView{

    
    float   offsetY=20;
    float   offsetLeft=15;
    float   offsetLableLeft=35;
    //  初始化标题
    if (self.alerTitle.length) {
        UILabel  *lableTitle=[[UILabel alloc]  initWithFrame:CGRectMake(offsetLableLeft, offsetY, self.viewAlert.frame.size.width-2*offsetLableLeft, 50)];
        lableTitle.text=self.alerTitle;
        lableTitle.numberOfLines=0;
        lableTitle.textColor=ALERT_TITLE_COLOR;
        lableTitle.font=[UIFont systemFontOfSize:18];
        lableTitle.textAlignment=NSTextAlignmentCenter;
        [self.viewAlert  addSubview:lableTitle];
        ;
        CGSize  sizeLable=[self  caculateHeightOfLable:lableTitle];
        [lableTitle  setFrame:CGRectMake(lableTitle.frame.origin.x, lableTitle.frame.origin.y, lableTitle.frame.size.width, sizeLable.height)];
        offsetY=lableTitle.frame.size.height+lableTitle.frame.origin.y+20;
        
    }
    
    //  初始化message
    if (self.alerMessage.length) {
        lableMessage=[[UILabel alloc]  initWithFrame:CGRectMake(offsetLableLeft, offsetY+5, self.viewAlert.frame.size.width-2*offsetLableLeft, 50)];
        lableMessage.text=self.alerMessage;
        lableMessage.font=[UIFont systemFontOfSize:17];
        lableMessage.numberOfLines=0;
        lableMessage.textAlignment=self.messageAlignment;
        lableMessage.textColor=ALERT_TITLE_COLOR;
        [self.viewAlert  addSubview:lableMessage];
        ;
        CGSize  sizeLable=[self  caculateHeightOfLable:lableMessage];
        [lableMessage  setFrame:CGRectMake(lableMessage.frame.origin.x, lableMessage.frame.origin.y, lableMessage.frame.size.width, sizeLable.height)];
        offsetY=lableMessage.frame.size.height+lableMessage.frame.origin.y+20;
        
    }
    
    // textField  文本框
    if (self.arrTextField) {
        
        for (int  i =0; i<self.arrTextField.count; i++) {
            
            UITextField  *textContent=self.arrTextField[i];
            [textContent  setFrame:CGRectMake(offsetLeft, offsetY, self.viewAlert.frame.size.width-2*offsetLeft, 40)];
            textContent.delegate=self;
            textContent.font=[UIFont systemFontOfSize:15];
            textContent.layer.masksToBounds=YES;
            textContent.layer.cornerRadius=2.0;
            textContent.layer.borderColor=[UIColor lightGrayColor].CGColor;
            textContent.layer.borderWidth=1.0;
            [self.viewAlert addSubview:textContent];
            
            offsetY+=textContent.frame.size.height+10;
            
        }
        offsetY+=10;
        ;
    }
    
    
    //  画分割线
    if (self.arrAlertAction.count) {
        offsetY+=5;
        UIImageView  *imageLine=[[UIImageView  alloc]  initWithFrame:CGRectMake(0, offsetY, self.viewAlert.frame.size.width, 1)];
        imageLine.backgroundColor=[UIColor  lightGrayColor];
        [self.viewAlert  addSubview:imageLine];
        offsetY+=imageLine.frame.size.height;
    }
    
    //    alertAction  按钮
    float  btnHeight=45;
    if (self.arrAlertAction.count) {
        for (int  i=0; i<self.arrAlertAction.count;i++) {
            
            CMCCIOTIGAlertActionCustomer  *alertActionCustomer=self.arrAlertAction[i];
            float  alertBtnWide=self.viewAlert.frame.size.width/self.arrAlertAction.count;
            UIButton  *btnAlert=[[UIButton  alloc]  initWithFrame:CGRectMake(i*alertBtnWide, offsetY, alertBtnWide, btnHeight)];
            [btnAlert setTitle:alertActionCustomer.title forState:UIControlStateNormal];
            btnAlert.tag=btnTag+i;
            [self  setBtnStyle:alertActionCustomer andBtn:btnAlert];
            [btnAlert  addTarget:self action:@selector(btnSelect:) forControlEvents:UIControlEventTouchUpInside];

            
            [self.viewAlert  addSubview:btnAlert];

            //               分割线
            if (i!=self.arrAlertAction.count-1) {
                UIImageView  *imageViewOffset=[[UIImageView  alloc]  initWithFrame:CGRectMake(btnAlert.frame.size.width-1, 0, 1, btnAlert.frame.size.height)];
                imageViewOffset.backgroundColor=[UIColor  lightGrayColor];
                [btnAlert  addSubview:imageViewOffset];
            }
            
        }
        
    }
  
    offsetY= self.arrAlertAction.count?(offsetY+btnHeight):offsetY;
    [self.viewAlert  setFrame:CGRectMake(0, 0, self.viewAlert.frame.size.width, offsetY)];
    [self addSubview:self.viewAlert];
    self.viewAlert.center=self.center;
    
    [[CMCCIOTIGSharePopWindow  sharedWindow]  setSubRect:self.viewAlert.frame];
    


}

-(void)setVerticalView{

    float   offsetY=0;
    float   offsetLeft=15;
    //  初始化标题
    if (self.alerTitle.length) {
        UILabel  *lableTitle=[[UILabel alloc]  initWithFrame:CGRectMake(offsetLeft, offsetY, self.viewAlert.frame.size.width-2*offsetLeft, 45)];
        lableTitle.text=self.alerTitle;
        lableTitle.numberOfLines=0;
        lableTitle.textColor=THEME_NAVIGATIONBAR_COLOR;
        lableTitle.font=[UIFont systemFontOfSize:16];
        lableTitle.textAlignment=NSTextAlignmentCenter;
        [self.viewAlert  addSubview:lableTitle];
        ;
        offsetY=lableTitle.frame.size.height+lableTitle.frame.origin.y;
        
        UIImageView  *imageViewOffset=[[UIImageView  alloc]  initWithFrame:CGRectMake(0, offsetY, self.viewAlert.Width, 1)];
        imageViewOffset.backgroundColor=[UIColor  lightGrayColor];
        [self.viewAlert  addSubview:imageViewOffset];
        
        
    }
    
    
    // textField  文本框
    if (self.arrTextField) {
        
        for (int  i =0; i<self.arrTextField.count; i++) {
            
            UITextField  *textContent=self.arrTextField[i];
            [textContent  setFrame:CGRectMake(0,offsetY, self.viewAlert.frame.size.width, 40)];
            textContent.delegate=self;
            textContent.font=[UIFont systemFontOfSize:15];
            textContent.layer.masksToBounds=YES;
            textContent.layer.cornerRadius=2.0;
            textContent.layer.borderColor=[UIColor lightGrayColor].CGColor;
            textContent.layer.borderWidth=1.0;
            [self.viewAlert addSubview:textContent];
            
            offsetY+=textContent.frame.size.height+10;
            
        }
    
    }
    
    [self addSubview:self.viewAlert];
    
    [self  setButton:offsetY];
  
}

-(void)setButton:(float)offsetY{
    
    for (UIView  *viewTem  in self.viewAlert.subviews ) {
        if ([viewTem isKindOfClass:[UIButton class]]) {
            [viewTem removeFromSuperview];
        }
    }
    //    alertAction  按钮
    float  btnHeight=45;
    
    if (self.arrAlertAction.count) {
        for (int  i=0; i<self.arrAlertAction.count;i++) {
            
            CMCCIOTIGAlertActionCustomer  *alertActionCustomer=self.arrAlertAction[i];
            UIButton  *btnAlert=[[UIButton  alloc]  initWithFrame:CGRectMake(0, offsetY, self.viewAlert.Width, btnHeight)];
            [btnAlert.titleLabel setFont:[UIFont systemFontOfSize:14]];
            btnAlert.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
            btnAlert.contentEdgeInsets = UIEdgeInsetsMake(0,20, 0, 0);
            [btnAlert setTitle:alertActionCustomer.title forState:UIControlStateNormal];
            btnAlert.tag=btnTag+i;
            [self  setBtnStyle:alertActionCustomer andBtn:btnAlert];
            
            [btnAlert  addTarget:self action:@selector(btnSelectMole:) forControlEvents:UIControlEventTouchUpInside];
            btnAlert.selected=alertActionCustomer.isSelect;
            [self.viewAlert  addSubview:btnAlert];
            
            //               分割线
            if (i!=self.arrAlertAction.count-1) {
                UIImageView  *imageViewOffset=[[UIImageView  alloc]  initWithFrame:CGRectMake(0, btnHeight-1, btnAlert.Width, 1)];
                imageViewOffset.backgroundColor=[UIColor  lightGrayColor];
                [btnAlert  addSubview:imageViewOffset];
            }
            
            offsetY+=btnHeight;
            
        }
        
    }
    
    if (offsetY>((screenHeight)-300 )) {
        [self.viewAlert  setFrame:CGRectMake(0, 0, 280, ((screenHeight)-300)) ]  ;
        
    }
    else{
        [self.viewAlert  setFrame:CGRectMake(0, 0, self.viewAlert.frame.size.width, offsetY)];
    }
    [self.viewAlert setContentSize:CGSizeMake(280, offsetY)];
    self.viewAlert.center=self.center;
    [[CMCCIOTIGSharePopWindow  sharedWindow]  setSubRect:self.viewAlert.frame];



}
//设置按钮样式

-(void)setBtnStyle:(CMCCIOTIGAlertActionCustomer *)alertActionCustomer andBtn:(UIButton  *)btnAlert{

    

    if (alertActionCustomer.alertActionStyle==UIAlertActionCustomeStyleCancel ) {
        
        [btnAlert setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        
//       点击时候的高亮状态
        [btnAlert setTitleColor:THEME_NAVIGATIONBAR_COLOR forState:UIControlStateHighlighted];
        
    }
    else if (alertActionCustomer.alertActionStyle==UIAlertActionCustomeStyleDefault){
        
        [btnAlert setTitleColor:THEME_NAVIGATIONBAR_COLOR forState:UIControlStateNormal];
    }
    else if (alertActionCustomer.alertActionStyle==UIAlertActionCustomeStyleDarkGray){
//       未选中
        [btnAlert setTitleColor:ALERT_TITLE_COLOR forState:UIControlStateNormal];
//  设置选中时候的状态
        [btnAlert  setBackgroundImage:[CMCCIOTIGUnity  getImageByUIView:btnAlert.bounds and:THEME_BACKGROUND_COLOR] forState:UIControlStateSelected];
        [btnAlert  setTitleColor:THEME_NAVIGATIONBAR_COLOR forState:UIControlStateSelected];
//       点击时候的高亮状态
        [btnAlert setTitleColor:THEME_NAVIGATIONBAR_COLOR forState:UIControlStateHighlighted];
    }
    else if (alertActionCustomer.alertActionStyle==UIAlertActionCustomeStyleBlack){
        [btnAlert setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//        //       点击时候的高亮状态
//        [btnAlert setTitleColor:THEME_NAVIGATIONBAR_COLOR forState:UIControlStateHighlighted];
        
    }
    else{
        
        
    }
    
    
    
}

#pragma mark  键盘 notification
-(void)initNotification{

    // 监听键盘弹出
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardAppearanceChanged:) name:UIKeyboardWillChangeFrameNotification object:nil];

}
- (void)keyboardAppearanceChanged:(NSNotification *)note
{
    NSDictionary *userInfo = [note userInfo];
    
    // Get the origin of the keyboard when it's displayed.
    NSValue* beginValue = [userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey];
    NSValue* endValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    // Get the top of the keyboard as the y coordinate of its origin in self's view's coordinate system. The bottom of the text view's frame should align with the top of the keyboard's final position.
    CGRect keyBoardRectBegin = [beginValue CGRectValue];
    CGRect keyBoardRectEnd = [endValue CGRectValue];
    
    // Get the duration of the animation.
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    // Animate the resize of the text view's frame in sync with the keyboard's appearance.
    [self moveInputBarWithKeyboardRectFrom:keyBoardRectBegin to:keyBoardRectEnd withDuration:animationDuration];
}
-(void)moveInputBarWithKeyboardRectFrom:(CGRect)rectBegin to:(CGRect)rectEnd withDuration:(NSTimeInterval)timeInternal{

    [UIView beginAnimations:@"changeAlertView" context:nil];
    [UIView setAnimationDuration:timeInternal];
    float keyBoardOriginY   = rectEnd.origin.y;
    if (keyBoardOriginY!=screenHeight) {
        self.viewAlert.frame= CGRectMake(self.viewAlert.frame.origin.x,keyBoardOriginY-self.viewAlert.frame.size.height-5, self.viewAlert.frame.size.width,self.viewAlert.frame.size.height);
    }
    else{
    
        self.viewAlert.center=self.center;
    }
    
    [UIView commitAnimations];

}

-(CGSize  )caculateHeightOfLable:(UILabel   *)lableTitle{

   #if __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_8_0
    
    return  [lableTitle.text sizeWithFont:lableTitle.font constrainedToSize:CGSizeMake(lableTitle.frame.size.width, MAXFLOAT) lineBreakMode:lableTitle.lineBreakMode];
    #else
    
    NSDictionary *attributes = @{NSFontAttributeName : lableTitle.font};
    return  [lableTitle.text boundingRectWithSize:CGSizeMake(lableTitle.frame.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    
    #endif

    
}

#pragma mark  添加数据

- (void)addAction:(CMCCIOTIGAlertActionCustomer *_Nonnull)action{

    [self.arrAlertAction  addObject:action];

}
- (void)addTextFieldWithConfigurationHandler:(textFieldBLock)configurationHandler{

    UITextField  *textContent=[[UITextField  alloc]  init];
    [self.arrTextField  addObject:textContent];
    configurationHandler(textContent);

}
#pragma mark  UITextField  deleget
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField  resignFirstResponder];
    return YES;
}

#pragma mark  属性get 方法

-(NSMutableArray  *)arrAlertAction{

    if (!_arrAlertAction) {
         _arrAlertAction=[NSMutableArray  new]     ;
    }
    return _arrAlertAction;
}
-(NSMutableArray  *)arrTextField{

    if (!_arrTextField) {
        _arrTextField=[NSMutableArray  new]     ;
    }
    return _arrTextField;

}
-(UIScrollView  *)viewAlert{
    
    if (!_viewAlert) {
        _viewAlert=[[UIScrollView  alloc]   initWithFrame:CGRectMake(0, 0, 280, 280)];
        _viewAlert.backgroundColor=[UIColor  whiteColor];
        _viewAlert.layer.masksToBounds=YES;
        _viewAlert.layer.cornerRadius=5;
        
    }
    
    return _viewAlert;
    
}
-(void)disMiCMCCIOTelf{
    //    消失的时候 移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
    
    [[CMCCIOTIGSharePopWindow  sharedWindow]  dismiss];
    

}

#pragma  mark 点击事件
//模式选择
-(void)btnSelectMole:(UIButton  *)btnTem{
    
    [self.arrAlertAction  enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
       
       UIButton  *btn=[self.viewAlert  viewWithTag:btnTag+idx ];
        btn.selected=NO;
        ;
    }];
    
    btnTem.selected=YES;
    
    
    [self  btnSelect:btnTem];

}
//alertview 点击事件
-(void )btnSelect:(UIButton  *)btnAlert{
    
    [self endEditing:YES];

    [self  disMiCMCCIOTelf];
    NSInteger  btnIndex=btnAlert.tag-btnTag;
    CMCCIOTIGAlertActionCustomer  *alertActionCustomer=self.arrAlertAction[btnIndex];
    alertActionCustomer.textFields=self.arrTextField;
    __weak  CMCCIOTIGAlertActionCustomer  *weakAlerCustomer=alertActionCustomer;
   
    alertActionCustomer.alertActionBlock(weakAlerCustomer);

}

-(void)reloadData{
    UITextField  *textSearch=self.arrTextField[0];
    [self  setButton: textSearch.bottomV+10];

}

@end

#pragma mark UIAlertActionCustomer 实现
@implementation CMCCIOTIGAlertActionCustomer
+ (_Nonnull instancetype)actionCustomerWithTitle:( NSString *_Nonnull)title style:(UIAlertActionCustomeStyle )style handler:(alertActionBlock)handler{

    CMCCIOTIGAlertActionCustomer  *alertActionCustomer=[[CMCCIOTIGAlertActionCustomer  alloc]  init];
    alertActionCustomer.title=title?title:@"";
    alertActionCustomer.alertActionStyle=style;
    alertActionCustomer.alertActionBlock=handler;
   
    return alertActionCustomer;

}
-(UIAlertActionCustomeStyle )alertActionStyle{

    return _alertActionStyle;
}

@end


